<template>
    <div class="white-box">
        <title-more title="秒杀活动设置" />
        <pub-panel title="秒杀活动" tip="开启后，用户可在前端参与秒杀商品活动" bottom="20px">
            <template #right>
                <el-switch
                    v-model="switch_one"
                    width="72px"
                    size="large"
                    inline-prompt
                    active-text="已开启"
                    inactive-text="已关闭"
                    @change="(val) => changeSwitch(val, 1)"
                />
            </template>
        </pub-panel>
        <!-- <pub-panel title="秒杀商品是否当天生成货架号" tip="开启后，秒杀商品当天生成货架号" bottom="20px">
            <template #right>
                <el-switch
                    v-model="switch_two"
                    width="72px"
                    size="large"
                    inline-prompt
                    active-text="已开启"
                    inactive-text="已关闭"
                    @change="(val) => changeSwitch(val, 2)"
                />
            </template>
        </pub-panel> -->
        <div class="task-one">
            <div class="task-one__item">
                <span class="task-one__label">设置秒杀时间：</span>
                <el-time-picker
                    v-model="skill_time"
                    is-range
                    format="HH:mm"
                    range-separator="至"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    @change="changeDates"
                />
            </div>
            <div class="task-one__btn">
                <el-button type="primary" :loading="form_loading" @click="handleTime">保存</el-button>
            </div>
        </div>
        <div class="table-mb">
            <el-button type="primary" @click="clickUpdate(1)">添加秒杀活动</el-button>
        </div>
        <div class="task-one">
            <div class="task-one__item">
                <span class="task-one__label">商品名称：</span>
                <el-input placeholder="输入商品名称" v-model.trim="skill_good_name" clearable></el-input>
            </div>
            <div class="task-one__btn">
                <el-button type="primary" :loading="search_btn" :icon="Search" @click="handleSearch">搜索</el-button>
            </div>
        </div>
        <el-tabs v-model="tabName" type="card" @tab-click="handleTab">
            <el-tab-pane :label="`${item.label}(${item.nums})`" :name="item.name" v-for="item in tabarr" :key="item.name">
                <el-table
                    class="table-mb"
                    v-loading="loading"
                    :data="arr_data"
                    :header-cell-style="{ background: '#F5F7FA' }"
                    element-loading-background="rgba(255, 255, 255, 0.6)"
                >
                    <el-table-column label="商品" min-width="300" fixed="left">
                        <template #default="{ row }">
                            <div class="table-lr">
                                <el-image
                                    class="table-lr__img"
                                    loading="lazy"
                                    :src="proxy.imgUrl + row.product_img + '!img_400'"
                                    fit="cover"
                                    v-if="row.product_img"
                                />
                                <div class="table-lr__right">
                                    <p class="lr-title line-one" style="font-size: 15px">{{ row.product_name }}</p>
                                    <p class="lr-text line-one">等级：{{ row.level }}</p>
                                    <p class="lr-text line-one">颜色：{{ row.color }}</p>
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="供应商" min-width="200">
                        <template #default="{ row }">
                            <p>{{ row.supplier.title }}[ID:{{ row.supplier_id }}]</p>
                            <p>
                                评分：<span style="color: #4b93fa">{{ row.supplier.avg_score }}星</span>
                            </p>
                        </template>
                    </el-table-column>
                    <el-table-column label="原供应价" min-width="120">
                        <template #default="{ row }">
                            <p class="table-price"><em>￥</em>{{ row.cost_price }}</p>
                        </template>
                    </el-table-column>
                    <el-table-column label="秒杀供应价" min-width="120">
                        <template #default="{ row }">
                            <p class="table-price"><em>￥</em>{{ row.seckill_price }}</p>
                        </template>
                    </el-table-column>
                    <el-table-column label="秒杀价" min-width="120">
                        <template #default="{ row }">
                            <p class="table-price"><em>￥</em>{{ row.product_price }}</p>
                        </template>
                    </el-table-column>
                    <el-table-column prop="total_num" label="秒杀数量" width="110"></el-table-column>
                    <el-table-column label="剩余数量" width="110">
                        <template #default="{ row }">
                            <p class="table-price">{{ row.total_num - row.sales <= 0 ? 0 : row.total_num - row.sales }}</p>
                        </template>
                    </el-table-column>
                    <el-table-column label="状态" width="100">
                        <template #default="{ row }">
                            <div style="color: #4b93fa">{{ row.status == 0 ? "已结束" : "进行中" }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="180" class-name="operation-nav" fixed="right">
                        <template #default="{ row }">
                            <!-- <el-button link type="primary" class="theme-btn" @click="clickExam(row)" v-if="item.name == 1">审核</el-button> -->
                            <el-button link type="primary" class="theme-btn" @click="clickUpdate(2, row)">编辑</el-button>
                            <el-button link type="primary" class="theme-btn" @click="clickSwitch(row)">{{ row.status == 0 ? "开启" : "关闭" }}</el-button>
                            <el-popconfirm title="是否确定删除？" confirm-button-text="确定" cancel-button-text="取消" @confirm="clickDel(row)">
                                <template #reference>
                                    <el-button link type="primary" class="theme-btn">删除</el-button>
                                </template>
                            </el-popconfirm>
                        </template>
                    </el-table-column>
                </el-table>
                <el-pagination
                    background
                    v-model:current-page="page"
                    v-model:page-size="pageSize"
                    :page-sizes="pageSizeNum"
                    :total="totalNums"
                    layout="total, sizes, prev, pager, next, jumper"
                >
                </el-pagination>
            </el-tab-pane>
        </el-tabs>

        <!-- 添加/编辑 -->
        <el-dialog
            v-model="dialogClass"
            :title="class_type == 1 ? '添加秒杀活动' : '编辑秒杀活动'"
            width="580px"
            :append-to-body="true"
            :destroy-on-close="true"
            :close-on-click-modal="false"
            @close="closeClass"
        >
            <el-form ref="ruleClassRef" :model="ruleClassForm" :rules="ruleCheckClass" label-width="120px">
                <el-form-item label="选择商品" prop="gid" required>
                    <div class="img-box flexs-center" @click.stop="dialogGoods = true" v-if="ruleClassForm.gid == ''">
                        <el-icon color="#999" size="26px">
                            <Plus />
                        </el-icon>
                    </div>
                    <div class="img-selects" v-else>
                        <el-image class="img-selects__pic" :src="proxy.imgUrl + goodObj.product_img + '!img_400'" fit="cover" />
                        <div class="img-del" @click.stop="delGood">
                            <el-icon size="14px" color="#fff"><CloseBold /></el-icon>
                        </div>
                    </div>
                </el-form-item>
                <el-form-item label="商品供应价">
                    <p>{{ ruleClassForm.cost_price }}</p>
                </el-form-item>
                <el-form-item label="秒杀供应价" prop="price">
                    <el-input v-model.trim="ruleClassForm.price" oninput="value=value.replace(/[^\d.]/g,'')" clearable placeholder="请输入秒杀供应价" />
                </el-form-item>
                <el-form-item label="秒杀数量" prop="nums">
                    <el-input v-model.trim="ruleClassForm.nums" oninput="value=value.replace(/[^\d]/g,'')" clearable placeholder="请输入秒杀数量" />
                </el-form-item>
                <el-form-item>
                    <div class="flexs" style="margin-top: 20px">
                        <el-button type="primary" :loading="form_loading" @click="submitForm(ruleClassRef)"> 确认 </el-button>
                        <el-button @click="resetForm(ruleClassRef)">重置</el-button>
                    </div>
                </el-form-item>
            </el-form>
        </el-dialog>

        <!-- 审核 -->
        <el-dialog v-model="dialogExam" title="秒杀活动审核" width="580px" :append-to-body="true" :destroy-on-close="true" @close="closeMoney">
            <el-form ref="ruleRef" :model="ruleForm" :rules="ruleCheck" label-width="120px">
                <el-form-item label="审核结果" prop="exam_type">
                    <el-radio-group v-model="ruleForm.exam_type">
                        <el-radio label="1">通过</el-radio>
                        <el-radio label="2">不通过</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="审核备注" prop="remarks">
                    <el-input v-model.trim="ruleForm.remarks" type="textarea" clearable :rows="5" placeholder="请输入审核备注" />
                </el-form-item>
                <el-form-item>
                    <div class="flexs" style="margin-top: 30px">
                        <el-button type="primary" :loading="form_loading" @click="submitExamForm(ruleRef)">确认审核</el-button>
                        <el-button @click="resetExamForm(ruleRef)">重置</el-button>
                    </div>
                </el-form-item>
            </el-form>
        </el-dialog>

        <!-- 商品列表 -->
        <el-dialog v-model="dialogGoods" :append-to-body="true" :destroy-on-close="true" title="商品列表" width="1000px" top="10vh" @close="closeGoods">
            <div class="task-one" style="margin-top: 0">
                <div class="task-one__item">
                    <el-input placeholder="请输入商品名称" v-model="good_name" @keyup.enter.native="goodSearch" clearable></el-input>
                </div>
                <div class="task-one__item">
                    <el-button type="primary" :loading="good_btn" :icon="Search" @click="goodSearch">搜索</el-button>
                </div>
            </div>
            <el-table
                class="table-mb"
                :data="goods"
                :header-cell-style="{ background: '#F5F7FA' }"
                element-loading-background="rgba(255, 255, 255, 0.6)"
                v-loading="table_loading"
            >
                <el-table-column prop="product_id" label="商品ID" width="90" fixed="left"></el-table-column>
                <el-table-column label="商品名称" min-width="200" fixed="left">
                    <template #default="{ row }">
                        <div class="table-lr">
                            <el-image class="table-lr__img" :src="proxy.imgUrl + row.product_img + '!img_400'" fit="cover" v-if="row.product_img" />
                            <div class="table-lr__right line-two">
                                <p>{{ row.product_name }}</p>
                                <p>颜色：{{ row.color }}</p>
                            </div>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="供应商" min-width="170">
                    <template #default="{ row }">
                        <p>{{ row.supplier_title }}[ID:{{ row.supplier_id }}]</p>
                    </template>
                </el-table-column>
                <el-table-column prop="cate_title" label="分类" width="120"></el-table-column>
                <el-table-column prop="level" label="等级" width="100"></el-table-column>
                <el-table-column label="规格" width="120">
                    <template #default="{ row }">
                        <p>{{ row.norm }}/{{ row.unit }}</p>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="90" fixed="right">
                    <template #default="{ row }">
                        <el-button color="#4B93FA" style="color: #fff" @click.stop="selectGoods(row)">选择</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination background v-model:current-page="good_page" :page-size="6" :total="good_total" layout="total, prev, pager, next, jumper">
            </el-pagination>
        </el-dialog>
    </div>
    <go-back />
</template>

<script setup>
import { getCurrentInstance, ref, onMounted, reactive, watch, computed, onBeforeUnmount } from "vue"
import { useBaseStore } from "@store/base"
import { CloseBold, Search, Plus } from "@element-plus/icons-vue"
import GoBack from "@components/GoBack.vue"
import OneLoad from "@mixins/one-load"
import TitleMore from "@components/title-more.vue"
import PubPanel from "@components/PubPanel.vue"

const { proxy } = getCurrentInstance()

const storeBase = useBaseStore()
const store_skill_time = computed(() => {
    return storeBase.skill_time
})

onMounted(() => {
    getConfig()
})

onBeforeUnmount(() => {})

const form_loading = ref(false) // 按钮状态

// 获取配置
const switch_one = ref(false) // 是否开启
const switch_two = ref(false) // 是否当天生成货架号
function getConfig() {
    proxy.$axios
        .get("ump/seckill/index", {
            params: {
                action: "config",
            },
        })
        .then((res) => {
            if (res.data.code == 0) {
                let result = res.data.data
                switch_one.value = result.seckill_status == 0 ? false : true
                skill_time.value = store_skill_time.value
                getCount(1)
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {})
}
// 设置配置
const changeSwitch = (val) => {
    proxy.$axios
        .get("ump/seckill/index", {
            params: {
                action: "config_set",
                field: "seckill_status",
                field_val: val ? 1 : 0,
            },
        })
        .then((res) => {
            if (res.data.code == 0) {
                proxy.$message({ message: "设置成功", type: "success" })
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {})
}

/**
 * tab切换
 * @param {String} status tab切换的类型值,[1:进行中,2:已结束,3:待审核,4:已拒绝]
 * @param {String} tabName 当前index
 * @param {Array} tabarr 数组
 */
const status = ref("1")
const tabName = ref("0")
const tabarr = ref([
    {
        label: "进行中的商品",
        name: "0",
        status: "1",
        nums: 0,
    },
    {
        label: "已结束",
        name: "1",
        status: "2",
        nums: 0,
    },
    // {
    //     label: "待审核",
    //     name: "2",
    //     status: "3",
    //     nums: 0,
    // },
    // {
    //     label: "审核不通过",
    //     name: "3",
    //     status: "4",
    //     nums: 0,
    // },
])
const handleTab = (pane) => {
    status.value = tabarr.value[pane.index].status
    getCount(2)
}
// 统计数量
function getCount(type = 1) {
    proxy.$axios
        .get("ump/seckill/index", {
            params: {
                action: "tongji",
            },
        })
        .then((res) => {
            if (res.data.code == 0) {
                let result = res.data.data
                tabarr.value[0].nums = result.start_count
                tabarr.value[1].nums = result.stop_count
                type == 1 && getList()
                type == 2 && pubRefreshParams(getList)
                type == 3 && pubParams(getList)
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {})
}

/**
 * minxin列表加载
 */
const { page, pageSizeNum, pageSize, loading, arr_data, totalNums, search_btn, pubParams, pubRefreshParams, getdata } = OneLoad()
// 切换每页显示条数
watch(pageSize, (val) => {
    page.value = 1
    pageSize.value = val
    pubParams(getList)
})
// 跳转第几页
watch(page, (val) => {
    page.value = val
    pubParams(getList)
})

function getList() {
    let params = {
        page: page.value,
        limit: pageSize.value,
        action: "index",
        type: status.value,
        so: skill_good_name.value,
    }
    getdata("ump/seckill/index", params)
}

// 搜索
const skill_good_name = ref("")
const handleSearch = () => {
    search_btn.value = true
    pubRefreshParams(getList)
}

/**
 * 添加/编辑
 * @param {Boolean} dialogClass 添加/编辑弹窗状态
 * @param {Number} class_type 1是添加，2是编辑
 * @param {Array} ruleClassRef 表单
 * @param {Object} ruleClassForm  表单字段
 * @param {Object} ruleCheckClass  表单提示
 * @param {Function} submitForm 提交表单
 */
const dialogClass = ref(false)
const class_type = ref(1)
const ruleClassRef = ref(null)
const ruleClassForm = reactive({
    id: "",
    gid: "",
    price: "",
    nums: "",
    cost_price: "0",
})
const ruleCheckClass = reactive({
    gid: [{ required: true, message: "请选择商品", trigger: "change" }],
    price: [{ required: true, validator: proxy.$util.validNumOrPoint, trigger: "blur" }],
    nums: [{ required: true, message: "请输入秒杀数量", trigger: "blur" }],
})
const submitForm = (formEl) => {
    if (!formEl) return
    formEl.validate((valid, fields) => {
        if (valid) {
            if (ruleClassForm.price - ruleClassForm.cost_price > 0) {
                proxy.$message({ message: "秒杀供应价不能高于原供应价！", type: "warning" })
                return
            }
            form_loading.value = true
            let data = {
                product_id: ruleClassForm.gid,
                seckill_price: ruleClassForm.price,
                total_num: ruleClassForm.nums,
            }
            if (class_type.value == 2) {
                data.seckill_id = ruleClassForm.id
            }
            let url = class_type.value == 1 ? "ump/seckill/add" : "ump/seckill/update"
            proxy.$axios
                .post(url, data)
                .then((res) => {
                    form_loading.value = false
                    if (res.data.code == 0) {
                        dialogClass.value = false
                        proxy.$message({ message: `${class_type.value == 1 ? "添加成功！" : "编辑成功！"}`, type: "success" })
                        class_type.value == 1 && getCount(3)
                        class_type.value == 2 && pubParams(getList)
                    } else {
                        proxy.$message({ message: res.data.msg, type: "error" })
                    }
                })
                .catch((err) => {
                    form_loading.value = false
                })
        }
    })
}
const resetForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
}
const closeClass = () => {
    dialogClass.value = false
    resetForm(ruleClassRef.value)
}
const clickUpdate = (type, row) => {
    class_type.value = type
    type == 1 && getGoods()
    dialogClass.value = true
    if (type == 2) {
        setTimeout(() => {
            class_type.value = 2
            ruleClassForm.id = row.seckill_id
            ruleClassForm.price = row.product_price
            ruleClassForm.nums = row.total_num
            ruleClassForm.gid = row.product_id
            ruleClassForm.cost_price = row.cost_price
            goodObj.value.product_img = row.product_img
            goodObj.value.product_id = row.product_id
        }, 50)
    }
}

/**
 * 选择商品和删除操作
 * @param {String} good_name 搜索字段
 * @param {Boolean} good_btn 搜索按钮状态
 * @param {Boolean} table_loading 表格加载
 * @param {Boolean} dialogSupplier 弹窗状态
 * @param {Number} good_page 页码
 * @param {Number} good_total 总数
 * @param {Array} goods 商品数组
 */
const good_btn = ref(false)
const table_loading = ref(false)
const dialogGoods = ref(false)
const good_page = ref(1)
const good_total = ref(0)
const good_name = ref("")
const goodObj = ref({})
const goods = ref([])
watch(good_page, (val) => {
    goods.value = []
    getGoods()
})
const goodSearch = () => {
    good_btn.value = true
    good_page.value = 1
    good_total.value = 0
    goods.value = []
    getGoods()
}
const selectGoods = (row) => {
    dialogGoods.value = false
    ruleClassForm.gid = row.product_id
    ruleClassForm.cost_price = row.cost_price || "0.00"
    goodObj.value = row
}
const closeGoods = () => {
    good_name.value = ""
    dialogGoods.value = false
}
const delGood = () => {
    ruleClassForm.gid = ""
    goodObj.value = {}
}
function getGoods() {
    table_loading.value = true
    proxy.$axios
        .get("ump/seckill/add", {
            params: {
                page: good_page.value,
                limit: 6,
                so: good_name.value,
            },
        })
        .then((res) => {
            table_loading.value = false
            good_btn.value = false
            if (res.data.code == 0) {
                let result = res.data.data
                good_total.value = res.data.count
                goods.value = result
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {
            good_btn.value = false
            table_loading.value = false
        })
}

/**
 * 审核-暂时废弃
 * @param {Boolean} dialogExam 弹窗状态
 * @property {Array} ruleRef 表单规则
 * @property {Object} ruleForm  表单字段
 * @property {Object} ruleCheck  表单提示
 */
const dialogExam = ref(false)
const ruleRef = ref(null)
const ruleForm = reactive({
    exam_type: "1", // 审核，1是通过，2不通过
    remarks: "",
})
const ruleCheck = reactive({
    exam_type: [{ required: true, message: "请选择审核结果", trigger: "change" }],
    remarks: [{ required: true, message: "请输入备注内容", trigger: "blur" }],
})
// 确认审核
const submitExamForm = (formEl) => {
    if (!formEl) return
    formEl.validate((valid, fields) => {
        if (valid) {
            form_loading.value = true
            let data = {
                exam_type: ruleForm.exam_type,
                remarks: ruleForm.remarks,
            }
            proxy.$axios
                .post("", data)
                .then((res) => {
                    form_loading.value = false
                    if (res.data.code == 0) {
                        dialogExam.value = false
                        proxy.$message({ message: "审核成功！", type: "success" })
                        pubParams(getList)
                    } else {
                        proxy.$message({ message: res.data.msg, type: "error" })
                    }
                })
                .catch((err) => {
                    form_loading.value = false
                })
        }
    })
}
const resetExamForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
}
const closeMoney = () => {
    dialogExam.value = false
    resetForm(ruleRef.value)
}
// 审核
const clickExam = (row) => {
    dialogExam.value = true
}

// 删除
const clickDel = (row) => {
    proxy.$axios
        .post("ump/seckill/delete", {
            seckill_id: row.seckill_id,
        })
        .then((res) => {
            if (res.data.code == 0) {
                getCount()
                pubParams(getList)
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {})
}

// 开启/关闭
const clickSwitch = (row) => {
    proxy.$axios
        .post("ump/seckill/status", {
            seckill_id: row.seckill_id,
            status: row.status == 0 ? 1 : 0,
        })
        .then((res) => {
            if (res.data.code == 0) {
                pubParams(getList)
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {})
}

// 设置秒杀时间
const skill_time = ref([])
const skill_format = ref([]) // 格式化后的时间
const changeDates = (val) => {
    if (val) {
        storeBase.setSkillTime(val) // 储存标准时间
        let time1 = proxy.$util.formatAtTimes(val[0])
        let time2 = proxy.$util.formatAtTimes(val[1])
        let skill_start_time = time1.substring(0, time1.length - 3)
        let skill_end_time = time2.substring(0, time2.length - 3)
        skill_format.value = [skill_start_time, skill_end_time]
    }
}
const handleTime = () => {
    if (skill_format.value.length == 0) {
        proxy.$message({ message: "请设置秒杀时间", type: "warning" })
        return
    }
    form_loading.value = true
    let s_time = skill_format.value.length > 0 ? skill_format.value[0] : ""
    let l_time = skill_format.value.length > 0 ? skill_format.value[1] : ""
    proxy.$axios
        .get("ump/seckill/index", {
            params: {
                action: "config_set",
                field: "seckill_time",
                field_val: s_time + "~" + l_time,
            },
        })
        .then((res) => {
            form_loading.value = false
            if (res.data.code == 0) {
                proxy.$message({ message: "保存成功！", type: "success" })
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {
            form_loading.value = false
        })
}
</script>
<script>
export default {
    name: "Seckill",
}
</script>

<style lang="less" scoped>
.table-price {
    font-size: @font-size-md;
    em {
        font-size: 13px;
    }
}
:deep(.el-tabs) {
    .el-tabs__header {
        box-sizing: content-box;
    }
    .el-tabs__item {
        background: #f7f8fa;
        border-bottom: 1px solid #e4e7ed;
        &.is-active {
            color: #303133;
            background: #fff;
        }
    }
}
</style>
